package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.IFacebookDao;
import com.cn.wanxi.model.FacebookModel;
import com.cn.wanxi.util.GetSqlSession;
import com.cn.wanxi.util.JDBCUtils;
import redis.clients.jedis.Jedis;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FacebookDaoImpl implements IFacebookDao {
    @Override
    public int deleteFacebook(int id) {
        return GetSqlSession.getSqlSession().update("com.cn.wanxi.dao.IFacebookDao.deleteFacebook", id);
    }

    @Override
    public List<FacebookModel> getFacebookList() {
        return GetSqlSession.getSqlSession().selectList("com.cn.wanxi.dao.IFacebookDao.getFacebookList");
    }

    @Override
    public FacebookModel getFacebook(int id) {
        return GetSqlSession.getSqlSession().selectOne("com.cn.wanxi.dao.IFacebookDao.getFacebook", id);
    }

    @Override
    public List<FacebookModel> getFacebooks(Map<String, Object> map) {
        return GetSqlSession.getSqlSession().selectList("com.cn.wanxi.dao.IFacebookDao.getFacebooks", map);
    }

    @Override
    public long getFacebookCount(Map<String, Object> map) {
        return GetSqlSession.getSqlSession().selectOne("com.cn.wanxi.dao.IFacebookDao.getFacebookCount",map);
    }

    @Override
    public List<FacebookModel> getFacebookListByRedis() {
        Jedis jedis = new Jedis();
        List<FacebookModel> facebookList = new ArrayList<>();
        List<String> facebookId = jedis.lrange("facebook_id",0,-1);
        for (int i = 0; i < facebookId.size(); i++) {
            FacebookModel facebookModel = new FacebookModel();
            facebookModel.setId(Integer.valueOf(facebookId.get(i)));
            facebookModel.setTitle(jedis.lindex("facebook_title", i));
            facebookModel.setEmail(jedis.lindex("facebook_email",i));
            facebookModel.setCreate_time(jedis.lindex("facebook_create_time",i));
            facebookModel.setContent(jedis.lindex("facebook_content", i));
            facebookList.add(facebookModel);
        }
        return facebookList;
    }

    @Override
    public void setFacebookInRedis(List<FacebookModel> facebookList) {
        Jedis jedis = new Jedis();
        for (FacebookModel facebook : facebookList) {
            jedis.rpush("facebook_id", String.valueOf(facebook.getId()));
            jedis.rpush("facebook_title", facebook.getTitle());
            jedis.rpush("facebook_email", facebook.getEmail());
            jedis.rpush("facebook_create_time", facebook.getCreate_time());
            jedis.rpush("facebook_content", facebook.getContent());
        }
    }

    @Override
    public int addFacebook(FacebookModel facebookModel) {
        return GetSqlSession.getSqlSession().insert("com.cn.wanxi.dao.IFacebookDao.addFacebook", facebookModel);
    }
}
